package com.ideal.manage.esms.service.diagnostic;

import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseManage;
import com.ideal.manage.esms.bean.diagnostic.DiagnoseResultInfo;
import com.ideal.manage.esms.bean.alarm.Alarm;
import com.ideal.manage.esms.bean.project.*;
import com.ideal.manage.esms.repository.diagnostic.DiagnoseManageRepository;
import com.ideal.manage.esms.repository.diagnostic.DiagnoseResultInfoRepository;
import com.ideal.manage.esms.repository.alarm.AlarmRepository;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.programme.ArithmeticDeployManageRepository;
import com.ideal.manage.esms.repository.programme.ArithmeticManageRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.service.alarm.AlarmService;
import com.ideal.manage.esms.util.DateBtnUtil;
import com.ideal.manage.esms.util.HttpRequests;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created By Dai On 2018/5/29
 * Remark: 诊断分析管理表 Service
 */
@Service
public class DiagnoseManageService {

    @Resource
    private DiagnoseManageRepository diagnoseManageRepository;
    @Resource
    private EquipmentManageRepository equipmentManageRepository;
    @Resource
    private ArithmeticManageRepository arithmeticManageRepository;
    @Resource
    private AlarmRepository alarmRepository;
    @Resource
    private DiagnoseResultInfoRepository diagnoseResultInfoRepository;
    @Resource
    private ArithmeticDeployManageRepository arithmeticDeployManageRepository;
    @Autowired
    private AlarmService alarmService;

    @Autowired
    private EntityManager entityManager;

    //入库诊断分析管理表
    public void saveDiagnoseInfo() {
        //设备的id,名称
        Map<String, String> eqMap = new HashMap<>();
        //算法的id,名称
        Map<String, String> thMap = new HashMap<>();
        //报警管理id,设备名称
        Map<String, String> alMap = new HashMap<>();
        //存放算法id,设备id
        Map<String, String> adMap = new HashMap<>();

        //存放算法name
        DiagnoseManage manage = new DiagnoseManage();
        //1.诊断设备
        List<EquipmentManage> manageList = equipmentManageRepository.findByisValid();
        for (EquipmentManage equipment : manageList) {
            eqMap.put(equipment.getId(), equipment.getName());
        }

        //2.诊断算法
        List<ArithmeticManage> arithmeticManageList = arithmeticManageRepository.findManages();
        for (ArithmeticManage arithmetic : arithmeticManageList) {
            thMap.put(arithmetic.getId(), arithmetic.getName());
        }
        //通过算法配置找到对应的设备id
        List<ArithmeticDeployManage> deployManages = arithmeticDeployManageRepository.findDeployManages();
        for (ArithmeticDeployManage aDm : deployManages) {
            adMap.put(aDm.getEquipmentId().getId(), aDm.getArithmeticId().getId());
        }

        //报警管理
        List<Alarm> alarmLists = alarmRepository.findAlarmByValid();
        for (Alarm alarms : alarmLists) {
            alMap.put(alarms.getId(), alarms.getEquipmentName());
        }
        //算法id
        String aId = "";
        //设备id
        String eqName = "";
        String eqId = "";
        //设备遍历
        for (Map.Entry<String, String> entry : eqMap.entrySet()) {
            for (Map.Entry<String, String> aentry : adMap.entrySet()) {
                if (entry.getKey().equals(aentry.getKey())) {
                    eqId = entry.getKey();
                    eqName = entry.getValue();
                    aId = aentry.getValue();
                    break;
                }
            }
        }
        //算法名称
        String arithName = "";
        for (Map.Entry<String, String> tentry : thMap.entrySet()) {
            if (aId.equals(tentry.getKey())) {
                arithName = tentry.getValue();
                break;
            }
        }
        //报警id
        String aid = "";
        for (Map.Entry<String, String> aentry : alMap.entrySet()) {
            if (aentry.getValue().equals(eqName)) {
                aid = aentry.getKey();
                break;
            }

        }
        List<DiagnoseManage> diagnoseM = diagnoseManageRepository.findDiagnoseManages();
        for (DiagnoseManage diagnoseManage : diagnoseM) {
            if (diagnoseManage.getEquipment().getId().equals(eqId)) {
                return;
            }
        }

        //3.诊断结果表入库
        List<DiagnoseResultInfo> allData = diagnoseResultInfoRepository.findDiagnoses();
        for (DiagnoseResultInfo diagnose : allData) {
            if (diagnose.getEquipment().getId().equals(eqId)) {
                String setVal = diagnose.getSetVal();
                String resultVal = diagnose.getResultVal();
                String diagnoseContent = setVal + resultVal;
                //入库
                manage.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                EquipmentManage eM = new EquipmentManage();
                eM.setId(eqId);
                manage.setEquipment(eM);
                manage.setEquipmentName(eqName);
                ArithmeticManage amanage = new ArithmeticManage();
                amanage.setId(aId);//算法id
                manage.setArithmetic(amanage);
                manage.setArithmeticName(arithName);
                manage.setDiagnoseContent(diagnoseContent);
                manage.setIsAlarm(1L);
                Alarm alarm = new Alarm();
                alarm.setId(aid);
                manage.setAlarm(alarm);
                manage.setIsAlarmThreshold(1L);
                manage.setCreateTime(new Date());
                manage.setIsValid(1L);
                diagnoseManageRepository.save(manage);
                break;
            }

        }

    }

    /**
     * 分页查询
     * 诊断结果查询
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        //增加删除标识的过滤
        SpecificationOperator isValid = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(isValid);
        MySpecification<DiagnoseManage> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<DiagnoseManage> page = diagnoseManageRepository.findAll(mySpecifications, pageable);
        //设置PageDto
        List<DiagnoseManage> diagnoseManages = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(diagnoseManages);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 时间的筛选
     *
     * @param request
     * @param condition
     * @return
     */
    public PageDto findConditionTime(HttpServletRequest request, List<String> condition,int pageNum) throws ParseException {
        //创建条件查询
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        for (int i = 0; i < condition.size(); i++) {
            //筛选按钮触发报警
            if (condition.get(i).equals("1")) {
                //封装条件
                SpecificationOperator operator = new SpecificationOperator("isAlarm", "2", "EQ");
                operators.add(operator);
                SpecificationOperator operator2 = new SpecificationOperator("isValid", "1", "EQ");
                operators.add(operator2);
                Sort sort = new Sort(Sort.Direction.DESC, "createTime");
                MySpecification<DiagnoseManage> mySpecification = new MySpecification<>(operators);
                //分页
                PageRequest pageRequest = new PageRequest(pageNum, 10,sort);
                Page<DiagnoseManage> page = diagnoseManageRepository.findAll(mySpecification, pageRequest);
                //设置PageDto
                List<DiagnoseManage> diagnoseManages = page.getContent();
                long total = page.getTotalElements();
                PageDto pageDto = new PageDto();
                pageDto.setRows(diagnoseManages);
                pageDto.setTotal(total);
                return pageDto;
            }
            //筛选按钮修改BMS报警阈值
            if (condition.get(i).equals("2")) {
                SpecificationOperator operator = new SpecificationOperator("isAlarmThreshold", "2", "EQ");
                operators.add(operator);
                SpecificationOperator operator2 = new SpecificationOperator("isValid", "1", "EQ");
                operators.add(operator2);

                Sort sort = new Sort(Sort.Direction.DESC, "createTime");
                MySpecification<DiagnoseManage> mySpecification = new MySpecification<>(operators);
                PageRequest pageRequest = new PageRequest(pageNum, 10,sort);

                Page<DiagnoseManage> page = diagnoseManageRepository.findAll(mySpecification, pageRequest);
                //设置PageDto
                List<DiagnoseManage> diagnoseManages = page.getContent();
                long total = page.getTotalElements();
                PageDto pageDto = new PageDto();
                pageDto.setRows(diagnoseManages);
                pageDto.setTotal(total);
                return pageDto;
            }
            if (condition.get(i).equals("createTime")) {
                //调用今日方法
                List<Date> dateLists = DateBtnUtil.today();
                Date today = dateLists.get(0);
                Date tomorrow = dateLists.get(1);
                SpecificationOperator operatorG = new SpecificationOperator("createTime", today, "GT");
                SpecificationOperator operatorL = new SpecificationOperator("createTime", tomorrow, "LT");
                operators.add(operatorG);
                operators.add(operatorL);
                continue;
            } else if (condition.get(i).equals("yestoday")) {
                //调用昨天处理的方法
                List<Date> dateLists = DateBtnUtil.yestoday();
                Date today = dateLists.get(0);
                Date yestoday = dateLists.get(1);
                SpecificationOperator operatorG = new SpecificationOperator("createTime", today, "GT");
                SpecificationOperator operatorL = new SpecificationOperator("createTime", yestoday, "LT");
                operators.add(operatorG);
                operators.add(operatorL);
                continue;
            } else if (condition.get(i).equals("week")) {
                //调用本周的处理方法
                List<Date> week = DateBtnUtil.week();
                Date monDay = week.get(0);
                Date sunDay = week.get(1);
                SpecificationOperator operatorG = new SpecificationOperator("createTime", monDay, "GT");
                SpecificationOperator operatorL = new SpecificationOperator("createTime", sunDay, "LT");
                operators.add(operatorG);
                operators.add(operatorL);
                continue;
            } else if (condition.get(i).equals("month")) {
                //调用本月处理方法
                List<Date> month = DateBtnUtil.month();
                Date mothFirst = month.get(0);
                Date mothLast = month.get(1);
                SpecificationOperator operatorG = new SpecificationOperator("createTime", mothFirst, "GT");
                SpecificationOperator operatorL = new SpecificationOperator("createTime", mothLast, "LT");
                operators.add(operatorG);
                operators.add(operatorL);
                continue;
            } else {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //自定义
                //获取开始时间
                String startTime = condition.get(0);
                Date start = dateFormat.parse(startTime);
                String endTime = condition.get(1);
                Date end = dateFormat.parse(endTime);
                SpecificationOperator operator = new SpecificationOperator("createTime", start, "GT");
                SpecificationOperator operator2 = new SpecificationOperator("createTime", end, "LT");
                operators.add(operator);
                operators.add(operator2);
            }
        }
        SpecificationOperator operator2 = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(operator2);
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        MySpecification<DiagnoseManage> mySpecification = new MySpecification<>(operators);
        PageRequest pageRequest = new PageRequest(pageNum, 10,sort);
        Page<DiagnoseManage> page = diagnoseManageRepository.findAll(mySpecification, pageRequest);
        //设置PageDto
        List<DiagnoseManage> diagnoseManages = page.getContent();
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(diagnoseManages);
        pageDto.setTotal(total);
        return pageDto;

    }
}



